﻿using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WMS.Model;
using WMS.Repository.IRepository;

namespace WMS.Repository
{
    public class DepartmentRepository : BaseRepository<DepartmentModel>, IDepartmentRepository
    {
        public DepartmentRepository(ISqlSugarClient db, ILogger<DepartmentRepository> logger) : base(db, logger)
        {
        }

        /// <summary>
        /// 获取部门下拉框（排除自己）
        /// </summary>
        public async Task<List<DepartmentModel>> GetDepartmentDropdownBoxAsync(long departmentId)
        {
            try
            {
                return await _db.Queryable<DepartmentModel>()
                               .Where(x => x.Id != departmentId)
                               .ToListAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取部门下拉框失败 - 排除部门ID: {departmentId}");
                throw;
            }
        }

        /// <summary>
        /// 查询部门是否存在
        /// </summary>
        public async Task<DepartmentModel> GetDepartmentNameAsync(string departmentName)
        {
            try
            {
                return await _db.Queryable<DepartmentModel>()
                               .Where(x => x.DepartmentName == departmentName)
                               .FirstAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询部门失败 - 部门名称: {departmentName}");
                throw;
            }
        }

        /// <summary>
        /// 部门分页模糊查询
        /// </summary>
        public async Task<PageResult<DepartmentModel>> GetDepartmentPagedListAsync(DepartmentQueryRequest request)
        {
            try
            {
                var query = _db.Queryable<DepartmentModel>();

                // 添加模糊查询条件
                if (!string.IsNullOrEmpty(request.DepartmentName))
                    query = query.Where(u => u.DepartmentName.Contains(request.DepartmentName));

                // 精确匹配状态
                if (request.Status.HasValue)
                    query = query.Where(u => u.Status == request.Status.Value);

                // 按创建时间倒序
                query = query.OrderBy(u => u.Id, OrderByType.Asc);

                // 执行分页查询
                RefAsync<int> totalCount = 0;
                var data = await query.ToPageListAsync(request.PageIndex, request.PageSize, totalCount);

                return new PageResult<DepartmentModel>
                {
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize,
                    TotalCount = totalCount,
                    TotalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize),
                    Data = data
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"部门分页查询失败 - 部门名称: {request.DepartmentName}, 状态: {request.Status}, 页码: {request.PageIndex}, 页大小: {request.PageSize}");
                throw;
            }
        }

        /// <summary>
        /// 获取部门昵称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<string> GetDepartmentNameById(long id)
        {
            try
            {
                return await _db.Queryable<DepartmentModel>()
                              .Where(x => x.Id == id).Select(x=> x.DepartmentName)
                              .FirstAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询部门失败 - 部门Id: {id}");
                throw;
            }
        }

        /// <summary>
        /// 批量获取部门名称
        /// </summary>
        async Task<Dictionary<long, string>> IDepartmentRepository.GetDepartmentNamesBatchAsync(List<long> departmentIds)
        {
            try
            {
                var departments = await _db.Queryable<DepartmentModel>()
                    .Where(x => departmentIds.Contains(x.Id))
                    .Select(x => new { x.Id, x.DepartmentName })
                    .ToListAsync();

                return departments.ToDictionary(x => x.Id, x => x.DepartmentName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量查询部门名称失败");
                return new Dictionary<long, string>();
            }
        }
    }
}